//
//  HMCharacteristicExt.swift
//  home
//
//  Created by Yun Zeng on 2019/10/7.
//  Copyright © 2019 Yun Zeng. All rights reserved.
//

import Foundation

// MARK: - 获取历史记录
extension HMCharacteristic {
    struct CharateristicQueryInfo: Codable {
        var aid: String
        var sid: Int
        var cid: Int
        var before: String?
        var after: String?
        var limit: Int?
    }
    
    func getHistory(completionHandler: @escaping (CloudMessage?) -> Void)  {
        guard let aid = self.service?.accessory?.id, let sid = self.service?.id else {
            return
        }
        
        let before = Date()
        let after = before.advanced(by: -TimeInterval(24 * 60 * 60))
        let info = CharateristicQueryInfo(aid: aid, sid: sid, cid: self.id, before: before.toString(), after: after.toString())
        let msg = CloudMessage(path: "home/characteristic/log", method: .get, object: info)
        msg.home = HomeManager.instance.current!.id
        let membership = Account.instance.membership
        
        _ = HttpClient.post(membership: membership, home: msg.home!, message: msg, completionHandler: completionHandler)
    }
    
    // 获取历史记录: 限制最大条数
    func getHistoryLimit(max: Int, completionHandler: @escaping (CloudMessage?) -> Void) {
        guard let aid = self.service?.accessory?.id, let sid = self.service?.id else {
            return
        }
        
        let info = CharateristicQueryInfo(aid: aid, sid: sid, cid: self.id, before: nil, after: nil, limit: max)
        let msg = CloudMessage(path: "home/characteristic/log", method: .get, object: info)
        msg.home = HomeManager.instance.current!.id
        let membership = Account.instance.membership
        
        _ = HttpClient.post(membership: membership, home: msg.home!, message: msg, completionHandler: completionHandler)
    }
    
}
